package main

import (
	"encoding/json"
	"fmt"
)

//protected 小写不能被json处理
type User struct {
	Id    int    `json:id` //重命名
	Name  string `json:-`  //不解析
	Addrs []string
	IsOk  bool `json:,string` //定义string类型
	Tel   int
}

func main() {
	//json 序列化 struct
	u0 := User{1, "tom", []string{"aaaa", "bbbb"}, true, 123}
	buf, err := json.Marshal(u0)
	if err != nil {
		return
	}
	var j string = string(buf)
	fmt.Println("user=", j)

	//json 序列化map
	m0 := make(map[string]interface{}, 4)
	m0["id"] = 123
	m0["name"] = "jack"
	m0["addrs"] = []string{"aaa", "bbb", "ccc"}
	m0["age"] = 20
	buf0, err0 := json.Marshal(m0)
	if err0 != nil {
		fmt.Println("err:", err0)
		return
	}
	fmt.Println("map=", string(buf0))

	//反序列化
	s1 := `{"Id":2,"Name":"jack","Addrs":["ccc","ddd"],"IsOk":false,"Tel":456}`
	var su1 User
	err1 := json.Unmarshal([]byte(s1), &su1)
	if err1 != nil {
		fmt.Println("err1=", err1)
		return
	}
	fmt.Println("su1=", su1)

	//反序列化map
	byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
	var dat map[string]interface{}
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	fmt.Println("map=", dat)
	num := dat["num"].(float64)
	fmt.Println("num=", num)
}
